const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/playground",{useUnifiedTopology: true,useNewUrlParser: true})
  .then(()=>{console.log('数据库连接成功')})
  .catch(err=>{console.log('数据库连接失败')})

//创建集合规则
let postSchema = new mongoose.Schema({
  title:{
    type: String,
    required: [true,'请出入文章标题'],
    minlength:[2,'文章长度不能小于2'],
    maxlength:[10,'文章长度不能大于10'],
    //去除字符串两边的空格
    trim:true
  },
  age:{
    type:Number,
    min:18,
    max:60
  },
  publishDate:{
    type:Date,
    //默认值
    default:Date.now
  },
  category:{
    type:String,
    enum:['html','css','javascript','node.js']
  },
  author:{
    type:String,
    //自定义验证规则
    validate:{
      validator:(v)=>{
        //返回布尔值,true验证成功，false验证失败，v是要验证的值
        return v && v.length>4
      },
      //自定义错误信息
      message:'出入的值不符合验证规则'
    }
  }
})

//使用规则创建集合
const Post = mongoose.model('postSchema',postSchema);
Post.create({title:'文章2',age:24,category:'html',author:'xiaduanjian'})
  .then(result=>{console.log(result)})
  .catch(error=>{
    const err = error.errors;
    for(let attr in err) {
      console.log(err[attr]['message']);
    }
  })
  